package pdf.to.markdown.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/pdf")
public class PdfController {
  
  /**
   * 表示 pdf 文件上传
   *
   * @param file 上传文件
   * @author lihh
   */
  @PostMapping("/upload")
  public void upload(MultipartFile file) throws IOException, DocumentException {
    // 定义 document 文档
    Document document = new Document();
    // 这里 拿到临时目录
    String tmpDir = System.getProperty("java.io.tmpdir");
    Path basePath = Paths.get(tmpDir), filenamePath = Paths.get(System.currentTimeMillis() + ".pdf");
    Path joinPath = basePath.resolve(filenamePath);
    
    // 构建 一个输出流
    FileOutputStream outputStream = new FileOutputStream(joinPath.toString());
    
    inputStreamToOutputStream(file.getInputStream(), outputStream);
    
    PdfWriter.getInstance(document, outputStream);
    document.open();
    
    System.out.println(document);
  }
  
  /**
   * 输入流 转换为 输出流
   *
   * @param inputStream  输入流
   * @param outputStream 输出流
   * @author lihh
   */
  public void inputStreamToOutputStream(InputStream inputStream, OutputStream outputStream) throws IOException {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, bytesRead);
    }
    inputStream.close();
    outputStream.close();
  }
}
